﻿using System;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using sqlserverextensions.Helper;

    [Serializable]
    [SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize = 8000)]
    public struct FileWriteAllLines : IBinarySerialize
    {
        private List<String> values;
        private String path;

        public void Init()
        {
            this.values = new List<string>();
        }

        public void Accumulate(SqlString Value, SqlString path)
        {
            this.values.Add(Value.Value);
            this.path = path.Value;
        }

        public void Merge(FileWriteAllLines Group)
        {
            this.values.AddRange(Group.values);
        }

        public SqlBoolean Terminate()
        {
            Int16 errSeverity = 16;

            try
            {
                File.WriteAllLines(path, values.ToArray());
                return true;
            }
            catch (Exception ex)
            {
                ExceptionHelper.EvaluateException(ex, errSeverity);
                return false;
            }
        }

        public void Read(BinaryReader r)
        {
            String s = r.ReadString();
            String[] sArray = s.Split(new char[] { '|' });
            List<String> list = new List<string>(sArray.Length);
            list.AddRange(sArray);
            this.values = list;

        }

        public void Write(BinaryWriter w)
        {

            w.Write(String.Join("|", values.ToArray()));
        }
    }
